// @ts-ignore
/* eslint-disable */

import { request, type RequestOptions } from '@/utils/request';
import SparkMD5 from "spark-md5";
import { Base64 } from "js-base64";
import helper from "@/utils/helper";

/**
 * 上传文件
 * @param input 文件信息
 * @returns
 */
export async function upload(input: FileInput, options?: RequestOptions) {
  return request<FileOut>(`file/upload`, {
    method: 'POST',
    data: input,
    ...(options || {}),
  });
}

/**
 * 下载文件
 * @param md5 文件MD5值
 * @returns
 */
export async function download(md5: string, options?: RequestOptions) {
  return request<Blob>(`file/download`, {
    method: 'POST',
    params: { md5 },
    responseType: 'blob',
    ...(options || {}),
  });
}

/**
 * 直接下载文件
 * @param md5 文件MD5值
 */
export function directdownload(md5: string) {
  const baseURL = import.meta.env.VITE_BASE_API_URL;
  window.open(`${baseURL}file/direct-download?md5=${md5}`);
}

/**
 * 增强下载功能
 * @param md5 文件MD5值
 * @returns
 */
export async function downloadex(md5: string, options?: RequestOptions) {
  return request<{
    fileContents: ArrayBuffer;
    contentType: string;
    fileDownloadName: string;
  }>(`file/download-ex`, {
    method: 'POST',
    params: { md5 },
    responseType: 'json',
    ...(options || {}),
  }).then(fileData => {
    if (fileData) {
      // 处理文件下载
      const blob = new Blob([fileData.fileContents], { type: fileData.contentType });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = fileData.fileDownloadName || md5;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    }
    return fileData;
  });
}

/**
 * 获取视频第一帧
 * @param md5 文件MD5值
 * @returns
 */
export async function firstFrame(md5: string, options?: RequestOptions) {
  return request<Blob>(`file/first-frame`, {
    method: 'GET',
    params: { md5 },
    responseType: 'blob',
    ...(options || {}),
  });
}

/**
 * 下载文件方式2
 * @param md5 文件MD5值
 * @returns
 */
export async function download2(md5: string, options?: RequestOptions) {
  return request<Blob>(`file/download2`, {
    method: 'GET',
    params: { md5 },
    responseType: 'blob',
    ...(options || {}),
  });
}

/**
 * 获取文件名
 * @param md5 文件MD5值
 * @returns
 */
export async function fileName(md5: string, options?: RequestOptions) {
  return request<String>(`file/file-name`, {
    method: 'GET',
    params: { md5 },
    ...(options || {}),
  });
}

/**
 * 上传头像文件（采用切片上传的方式）
 * @param file 文件对象
 * @returns 返回上传成功后的文件MD5值和URL
 */
export async function uploadAvatar(file: File): Promise<{ md5: string, url: string }> {
  return new Promise((resolve, reject) => {
    const fileName = file.name;
    let fileReader = new FileReader();
    let spark = new SparkMD5.ArrayBuffer();
    fileReader.readAsArrayBuffer(file);
    fileReader.onload = async (e) => {
      try {
        let buffs = e.target?.result as ArrayBuffer;
        spark.append(buffs);
        // 获取MD5
        let md5 = spark.end();
        
        // 切片上传，每片1MB
        const chunckSize = 1 * 1024 * 1024;
        const totalChunk = Math.ceil(buffs.byteLength / chunckSize);
        
        for (let i = 0; i < totalChunk; i++) {
          const start = i * chunckSize;
          const end = Math.min(start + chunckSize, buffs.byteLength);
          const data = new Uint8Array(buffs.slice(start, end));
          const base64 = Base64.fromUint8Array(data);
          
          const result = await request<FileOut>(`file/upload`, {
            method: 'POST',
            data: { 
              totalChunk: totalChunk, 
              name: fileName, 
              md5: md5, 
              data: base64, 
              size: buffs.byteLength, 
              currentChunk: i + 1 
            },
          });
          
          if (result?.exists === true) {
            helper.toast("秒传成功!");
            break;
          }
          
          if (!result || result?.currentSuccess !== true) {
            const errorMsg = result?.msg;
            helper.error(errorMsg || "上传失败");
            reject(new Error(errorMsg || "上传失败"));
            return;
          }
          
          // 续传
          if (result.lastChunk !== -1) {
            i = result.lastChunk;
          }
        }
        
        resolve({ 
          md5: md5, 
          url: helper.toApiUrl("file/download2?md5=" + md5) 
        });
      } catch (error) {
        console.error("头像上传失败:", error);
        reject(error);
      }
    };
    
    fileReader.onerror = (error) => {
      reject(error);
    };
  });
}
